package me.zingon.redis;

import me.zingon.model.User;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

@Component("MyKeyGenerator")
public class MyKeyGenerator implements KeyGenerator {
    @Override
    public Object generate(Object target, Method method, Object... params) {
        StringBuilder sb=new StringBuilder();

        Cacheable cacheable=method.getAnnotation(Cacheable.class);
        CachePut cachePut=method.getAnnotation(CachePut.class);
        CacheEvict cacheEvict=method.getAnnotation(CacheEvict.class);
        String[] values;
        if(cacheable!=null)
            values=cacheable.value();
        else if (cachePut!=null)
            values=cachePut.value();
        else if(cacheEvict!=null)
            values=cacheEvict.value();
        else
            values= new String[]{method.getName()};
        for (String value:values) {
            sb.append("_");
            sb.append(value);
        }
        for(Object o:params){
            sb.append("_");
            if(o instanceof HttpSession){
                HttpSession session = (HttpSession) o;
                User user= (User) session.getAttribute("user");
                if(user!=null)
                    sb.append(user.getStuId());
                else
                    sb.append(o.toString());
            }else
                sb.append(o.toString());
        }
        return sb.toString();
    }
}
